<?php

class MemberAction extends IntesysAction
{

    function index()
    {
        // $list=$this->dao->alias('m')->join('left join __SITE__ s on s.id=m.site_id')->join('left join __MEMBER_GROUP__ g on g.id=m.group_id')->join('left join __MEMBER_GROUP__ g2 on g2.id=g.pid')->where(array('m.id'=>session(C('USER_AUTH_KEY'))))->Field('m.*,s.title as sitename,g.title as groupname,g2.title as departname')->select();
        // $this->assign('nlist',$list[0]);
        // $rule=D('Integral_rule')->where(array('site_id'=>__SITEID__))->Field('id,name')->select();
        // $this->assign('rule',$rule);
        //
        // //获取任务列表
        // import("@.ORG.Task.Task_daily");
        // $this->task=new Task_daily();
        // $this->assign('tasklist',$this->task->getInfos($this->task->filter()));
        //
        // //获取审核列表
        // $this->initView();
        // D('Mission')->_list($this->view,['approver'=>['like','%'.session(C('USER_AUTH_KEY')).'%']]);
        //
        // //个人日志列表（本部门所有人）
        // $group=D('member')->where('id ='.$this->UserInfo)->find();
        // $groupid=$group['group_id'];//获取分类id
        // $group=D('member_group')->where('id = '.$groupid)->find();
        // if($group['pid']!=0){
        // $group=D('member_group')->where('id = '.$group['pid'])->find();
        // $groupid=$group['id'];
        // }else{
        // $groupid=$group['id'];
        // }
        // $loglist = D('info')->join("think_member on think_member.id = think_info.member_id ")->join('think_member_group on think_member_group.id = '.$groupid)->where("think_info.type = 'log' ")->field('think_info.*,think_member.img_url as img,think_member_group.name as name,think_member.nickname as nickname')->select();
        // $this->assign('loglist',$loglist);
        
        // 个人积分统计
        
        // $this->stime = time();
        //
        //
        // //个人月积分趋势图数据
        // $map4['member_id']=$this->UserInfo;
        // // var_dump($map4['member_id']);exit;
        // // $map4['time']=array('between',array(time(date('Y-m',time())),time());
        // // var_dump($map4['time']);exit;
        // $map4['statu_id']=array('in','0,1');
        // $memberMonthlist=M('integral_log')->where($map4)->Field('changenum,time')->select();
        // $this->assign('memberlist',$memberMonthlist);
        // var_dump($memberMonthlist);exit;
        
        // 积分总数写入integral_log表
        // $sel=D('integral_log')->select();
        // $arr=array();
        // foreach($sel as $key =>$value){
        // if(!array_key_exists($value['member_id'], $arr)){//不存在该用户
        // //用户不存在,就让total=0;
        // //$arr[$value['member_id']]=0;
        // $arr = array_merge(array($value['member_id'] => 0), $arr);
        // }
        // $data['totalnum']=intval($value['changenum'])+intval($arr[$value['member_id']]);
        // $arr[$value['member_id']]=$data['totalnum'];
        // D('integral_log')->where('id = '.$value['id'])->save($data);
        //
        // }
        // var_dump($arr);exit;
        $this->display();
    }

    public function edit()
    {
        if ($_POST['symbol'] == 1) {
            $data['tel'] = $_POST['tel'];
            $data['Email'] = $_POST['Email'];
            $data['QQ'] = $_POST['QQ'];
            $data['remark'] = $_POST['remark'];
            $data['id'] = $this->memberInfo['id'];
            $r = D('Member')->save($data);
        }
        $this->info = D('Member')->where('id = ' . $this->memberInfo['id'])->find();
        $this->newform = D('Mission')->where('member_id=' . $this->memberInfo['id'] . ' and particular=2')->getField('formtemplate');
        if ($this->newform == false) {
            $this->initView();
            $this->newform = D('Form')->where(array(
                'particular' => 2,
                'site_id' => __SITEID__
            ))->createTaskForm($this->view);
        }
        $this->display();
    }
    // 验证旧密码并修改密码
    public function modifyPwd()
    {
        $result = 0;
        if (IS_POST) {
            if ($this->userInfo['password'] == md5($_POST['oldPwd'])) {
                $result = $this->dao->where('id=' . $this->userInfo['id'])->setField('password', md5($_POST['password']));
                if (! $result) {
                    $result = 0;
                    $info = $this->dao->getError();
                } else {
                    $result = 1;
                    $info = 'success';
                }
            } else {
                $info = '密码错误';
            }
        } else {
            $info = '连接错误';
        }
        echo (json_encode([
            'status' => $result,
            'info' => $info
        ]));
    }

    public function update()
    {
        if (session(C('USER_AUTH_KEY'))) {
            $_POST['id'] = session(C('USER_AUTH_KEY'));
            if (isset($_POST['Email'])) {
                $_POST['Email'] = strip_tags($_POST['Email']);
            }
            if (isset($_POST['tel'])) {
                $_POST['tel'] = (int) $_POST['tel'];
            }
            if (isset($_POST['QQ'])) {
                $_POST['QQ'] = (int) $_POST['QQ'];
            }
            if (isset($_POST['address'])) {
                $_POST['address'] = strip_tags($_POST['address']);
            }
            if (isset($_POST['password'])) {
                $_POST['password'] = md5($_POST['password']);
            }
            
            $this->dao->where(array(
                'id' => $this->memberInfo['id']
            ))->save(array(
                'setup' => 1
            ));
            
            parent::update();
        }
    }

    public function getMemberGroup()
    {
        $this->initView();
        D('Member')->getMemberView($this->view);
    }

    public function getMemberGroupRadio()
    {
        $this->initView();
        D('Member')->getMemberView($this->view, 'member_radio');
    }
    
    // APP 获取一个信息
    public function getInfo()
    {
        if ($this->_post('userId') && $this->_post('requestType') == 101) {
            $map = 'id=' . $this->_post('userId') . ' and site_id=' . __SITEID__;
            $info = $this->dao->where($map)
                ->Field([
                'id' => 'userId',
                'name',
                'tel' => 'phone',
                'img_url' => 'userIcon',
                'group_id' => 'group',
                'QQ',
                'Email',
                'address',
                'remark',
                'position_id' => 'position'
            ])
                ->find();
            $status = $info ? 1 : 0;
            die(json_encode([
                'status' => $status,
                'data' => $info
            ]));
        }
    }
    // APP 获取多个信息
    public function getInfos()
    {
        if ($this->_post('requestType') == 100) {
            $map = ' site_id=' . __SITEID__ . ' and group_id!=0';
            $info = $this->dao->where($map)
                ->Field([
                'id' => 'userId',
                'name',
                'tel' => 'phone',
                'img_url' => 'userIcon',
                'group_id' => 'group',
                'QQ',
                'Email',
                'address',
                'remark',
                'position_id' => 'position'
            ])
                ->select();
            $status = $info ? 1 : 0;
            die(json_encode([
                'status' => $status,
                'data' => $info
            ]));
        }
    }
    
    // 选择列表
    public function select()
    {
        $this->pagesize = 7;
        $this->listmap = "site_id = " . __SITEID__;
        $this->listmap .= " and group_id <> 0 ";
        if (isset($_GET['selected'])) {
            $selected = $this->_get('selected');
            if ($selected == '') {
                $selected = 0;
            }
            $this->pagesize = 100;
            $this->listmap = "id in(" . $selected . ")";
        }
        if ($this->_param('keywords')) {
            $keywords = $this->_param('keywords');
            $_GET['keywords'] = urlencode($this->_param('keywords'));
            $this->listmap .= " and title like '%{$keywords}%'";
            $this->keywords = $keywords;
        }
        parent::_list();
        $this->display();
    }
    
    // 选择列表
    public function selectText()
    {
        $this->pagesize = 7;
        $this->listmap = "site_id = " . __SITEID__;
        $this->listmap .= " and group_id <> 0 ";
        if (isset($_GET['selected'])) {
            $selected = $this->_get('selected');
            if ($selected == '') {
                $selected = 0;
            }
            $this->pagesize = 100;
            $this->listmap = "id in(" . $selected . ")";
        }
        if ($this->_param('keywords')) {
            $keywords = $this->_param('keywords');
            $_GET['keywords'] = urlencode($this->_param('keywords'));
            $this->listmap .= " and nickname like '%{$keywords}%'";
            $this->keywords = $keywords;
        }
        if ($this->_param('position')) {
            $position_id = $this->_param('position');
            $this->listmap .= " and memberpositionid like '%," . $position_id . ",%'";
        }
        $this->positionList = M('member_position')->where([
            'site_id' => __SITEID__
        ])
            ->field('id,name')
            ->select();
        parent::_list();
        $this->display();
    }

    public function departlist()
    {
        $this->pagesize = 7;
        $this->listmap = "site_id = " . __SITEID__;
        $this->listmap .= " and group_id <> 0 ";
        if (isset($_GET['selected'])) {
            $selected = $this->_get('selected');
            if ($selected == '') {
                $selected = 0;
            }
            $this->pagesize = 100;
            $this->listmap = "id in(" . $selected . ")";
        }
        if ($this->_param('keywords')) {
            $keywords = $this->_param('keywords');
            $_GET['keywords'] = urlencode($this->_param('keywords'));
            $this->listmap .= " and( nickname like '%{$keywords}%' or name like '%{$keywords}%') ";
            $this->keywords = $keywords;
        }
        if ($this->_param('position')) {
            $position_id = $this->_param('position');
            $this->listmap .= " and memberpositionid like '%," . $position_id . ",%'";
        }
        $memberpositiondb = M('Member_position');
        $this->positionList = $memberpositiondb->where([
            'site_id' => __SITEID__
        ])
            ->field('id,name')
            ->select();
        parent::_list();
        $list = $this->list;

        foreach ($list as $k => $v) {
            $postionid = explode(',', $v['memberpositionid']);
            $memberpositionid[] = 0;
            /*foreach ($postionid as $key => $val) {
                if (intval($val) > 0) {
                    $memberpositionid[] = $val;
                }
            }
            $list[$k]['position'] = $memberpositiondb->where(array(
                'site_id' => __SITEID__,
                'id' => array(
                    'in',
                    implode(',', $memberpositionid)
                )
            ))
                ->Field('name')
                ->select();*/	
				$list[$k]['position']=$v['memberpositionname'];
        }
        $this->assign('list', $list);
        $this->display();
    }
    
    // 获取当前月份的第一天和最后一天（array(第一天，第二天)）
    private function getCurMonthDay()
    {
        return [
            strtotime(date('Y-m-01 00:00:00', time())),
            strtotime(date('Y-m-d 23:59:59', strtotime(date('Y-m-01 00:00:00', time()))) . ' +1 month -1 day')
        ];
    }

    public function ExcelToSql()
    {
        $pp = './Public/Uploads/' . __SITEID__ . '/';
        if (! file_exists($pp)) {
            mkdir($pp, 0755);
        }
        
        if (! file_exists($pp . '/tmp/')) {
            mkdir($pp . '/tmp/', 0755);
        }
        import('ORG.Util.ExcelToArrary'); // 导入excelToArray类
        
        $name = date('_YmdHis');
        if (file_exists($file)) {}
        ;
        
        if (! empty($_FILES['file_stu']['name'])) {
            $i = 2; // 错误提示信息行数，数据从第二行开始
            import('ORG.Net.UploadFile');
            $upload = new UploadFile(); // 实例化上传类
            
            $upload->allowExts = array(
                'xls',
                'xlsx'
            ); // 设置附件上传类型
            $maxSize = 102400;
            
            if ($_FILES['file_stu'][size] > $maxSize) {
                $this->error("上传文件太大");
            }
            
            $upload->savePath = $pp; // 设置附件上传目录
            
            if (! $upload->upload()) { // 上传错误提示错误信息
                $this->error($upload->getErrorMsg());
            } else { // 上传成功 获取上传文件信息
                $info = $upload->getUploadFileInfo();
            }
        } else {
            $this->error('你没有上传文件');
        }
        
        $m = M('Member');
        $allAdded = true;
        $ExcelToArrary = new ExcelToArrary(); // 实例化
        
        file_exists($_FILES['file_stu']['name']);
        file_exists($_FILES['file_stu']['tmp_name']);
        
        $res = $ExcelToArrary->read($info[0]['savepath'] . $info[0]['savename'], "UTF-8", $info[0]['extension']); // 传参,判断office2007还是office2003
                                                                                                                  
        // 表头是否正确
        /*
         * if ($hear[0] != "工号") {
         * $this->error("表头设置错误，重新设置");
         * }
         */
        $res = array_slice($res, 1); // 去表头
        $res = array_slice($res, 1); // 去表头
        $filename = './Public/Uploads/' . __SITEID__ . '/' . $info[0]['savename'];
        unlink($filename);
        $hear = $res[1];
        
        session($_SESSION['memberInfo']['id'] . 'all', serialize($res));
        
        $this->fenye($_GET['page']);
        exit();
        /*
         * $m->startTrans();
         * $new = array();
         *
         * exit();
         * foreach ($res as $k => $v) { // 循环excel表
         *
         * foreach ($v as $vk => $vv) {
         * if ($v[$vk] == "") {
         * unset($v[$vk]);
         * }
         * }
         *
         * if ($v[0] != "") {
         *
         * $data[$k]['name'] = $v[0]; // 创建二维数组
         * } else {
         * continue;
         * }
         *
         * $data[$k]['tel'] = trim($v[1]);
         * $data[$k]['Email'] = trim($v[2]);
         * $data[$k]['graduatefrom'] = trim($v[4]);
         *
         * $data[$k]['address']=trim($v[5]);
         * $data[$k]['pid']=$_GET['pid'];
         * $data[$k]['gid']=$_GET['gid'];
         *
         *
         * if (trim($v[3]) == '女') {
         * $data[$k]['sex'] = 0;
         * } else {
         * $data[$k]['sex'] = 1;
         * }
         *
         * // $result = $m->add($data[$k]);
         * //if (! $result) {
         * // $m->rollback();
         *
         * // $this->error('提交數據出錯，請重新提交。');
         * // }
         *
         * $i ++;
         * }
         * dump($data);
         *
         * $filename = './Public/Uploads/loadExcel/' . $info[0]['savename']; // 上传文件绝对路径,unlink()删除文件函数
         * if (unlink($filename)) {
         * if ($i < 201) {
         * echo "文件删除成功";
         * // $m->commit(); // 成功则提交
         * } else {
         * // $m->rollback(); // 不成功，则回滚
         *
         * // $this->error('提交數據出錯，請重新提交。');
         * }
         *
         * // $this->success('导入成功');
         * } else {
         * echo "文件并没有删除成功";
         * // $this->error('缓存删除失败，请告诉管理员');
         * }
         *
         * exit();
         */
    }

    public function avatar()
    {
        $this->display();
    }

    public function returnText($text)
    {
        return "<script>parent.document.getElementById('Excelinfo').innerHTML='$text';</script>";
        /*
         * 因为表单设定，跳转页面是iframe，所以写js首先，要通过iframe的dom对象parent，获得upload.html主页面
         * dom对象，才能通过document.getElementById('info')获取页面上的<h2 id='info'></h2> dom对象，从而显示提示信息。
         */
    }

    public function fenye($page)
    {
        $num = 1;
        
        if ($data == null) {
            
            $data = unserialize(session($_SESSION['memberInfo']['id'] . 'all'));
        }
        
        $groupData = M('member_group')->where('site_id=' . __SITEID__)
            ->Field('id,title')
            ->select();
        
        $positionData = M('Member_position')->where('site_id=' . __SITEID__)
            ->Field('id,name')
            ->select();
        
        $count = 0;
        foreach ($data as $val) {
            $count ++;
        }
        if (isset($page)) {
            
            @$page = max(1, intval($_GET["page"]));
            $pagesize = 10;
            $startindex = ($page - 1) * $pagesize;
            $table .= '<table class="display table table-bordered table-hover table-striped"><tr><td>工号</td><td>部门/职位</td><td>姓名</td><td>性别</td><td>角色</td><td>电话</td><td>员工状态</td><td>入职时间</td></tr>';
            for ($i = 0; $i <= 50; $i ++) {
                if ($data[$i][0] == '') {
                    break;
                }
                if ($page == 1) {
                    if ($i < 10) {
                        $j = 'inline';
                    } else {
                        $j = 'none';
                    }
                } else {
                    if ($i < 10) {
                        $j = 'none';
                    } else {
                        $j = 'inline';
                    }
                }
                
                // 部门转成成下拉框形式
                $member = '';
                $popt = '';
                
                $member .= '<select style="width:120px" class="form-cont" name="member[]">';
                
                $thisss = 0;
                foreach ($positionData as $pkey => $pval) {
                    $is_popt = '';
                    
                    if ($data[$i]['1'] == $pval['name']) {
                        $is_popt = 'selected="selected"';
                        $thisss = 1;
                    }
                    $popt .= '<option value="' . $pval['id'] . '"  ' . $is_popt . '>' . $pval['name'] . '</option>';
                    $style[$i] = '';
                }
                
                if ($thisss != 1) {
                    
                    $style[$i] = 'style="background-color:#FF6C60;"';
                    $error = '<label>提醒：共有' . $num . '条信息设置有误，请修改</label>';
                    $num ++;
                }
                
                $member .= $popt;
                $member .= '</select>';
                
                // 角色
                $role = '';
                $opt = '';
                
                $role .= '<select style="width:120px" class="form-cont" name="role[]">';
                
                foreach ($groupData as $key => $val) {
                    $is_opt = '';
                    if ($data[$i]['4'] == $val['title']) {
                        $is_opt = 'selected="selected"';
                    }
                    $opt .= '<option value="' . $val['id'] . '"  ' . $is_opt . '>' . $val['title'] . '</option>';
                }
                $role .= $opt;
                $role .= '</select>';
                // 性别
                $is_man = '';
                $is_women = '';
                if ($data[$i][3] == '男') {
                    $is_man = 'selected';
                } elseif ($data[$i][3] == '女') {
                    $is_women = 'selected';
                }
                $sex = '<select style="width:80px" class="form-cont" name="sex[]"><option value="1"' . $is_man . '>男</option><option value="0"  ' . $is_women . '>女</option>';
                
                if ($data[$i][0] != '') {
                    
                    $str .= '<tr><td><input class="form-cont" name="id[]" type="text" value="' . $data[$i][0] . '" style="width:100px"></td><td ' . $style[$i] . '>' . $member . '</td><td><input class="form-cont"  name="name[]"  type="text" value="' . $data[$i][2] . '" style="width:100px"></td><td>' . $sex . '</td><td style="text-align:center">' . $role . '</td><td><input class="form-cont"   style="width:150px" name="phone[]"  datatype="m" errormsg="请输入正确的手机号码" type="text" value="' . $data[$i][5] . '"></td><td><input class="form-cont"  name="state[]" type="text" value="' . $data[$i][6] . '" style="width:100px"></td><td width="100"><input class="form-cont"  style="width:100px" name="time[]" type="text" value="' . $data[$i][7] . '"></td></tr>';
                }
            }
            $str .= '</table>';
            
            $pagenum = @ceil($count / $pagesize);
            /*
             * for ($i = 1; $i <= $pagenum; $i ++) {
             * if ($count < $pagesize) {
             * break;
             * }
             * if ($page == $i) {
             * $str .= '<a href="javascript:void(0)" onclick=ajaxfunction(' . $i . ')>[' . $i . ']</a>&nbsp;&nbsp;&nbsp;';
             * } else {
             * $str .= '<a href="javascript:void(0)" onclick=ajaxfunction(' . $i . ')>' . $i . '</a>&nbsp;&nbsp;&nbsp;';
             * }
             * }
             */
            
            if (isset($_GET['pd'])) {
                
                $pd = $_GET['pd'];
            } else {
                $pd = 1;
            }
            session($_SESSION['memberInfo']['id'] . 'all', null);
            $error .= $table;
            $table = $error;
            $table .= $str;
            if ($pd == 1) {
                echo $this->returnText($table);
            } else {
                echo $str;
            }
        } else {
            die();
        }
    }

    public function upload()
    {
        $this->display();
    }
    // 上传头像
    public function uploadImg()
    {
        import('ORG.Net.UploadFile');
        $upload = new UploadFile(); // 实例化上传类
        $upload->maxSize = 1024 * 1024; // 设置上传图片的大小
        $upload->allowExts = array(
            'jpg',
            'png',
            'gif'
        ); // 设置上传图片的后缀
        $upload->uploadReplace = true; // 同名则替换
        $upload->saveRule = 'uniqid'; // 设置上传头像命名规则(临时图片),修改了UploadFile上传类
                                      // 完整的头像路径
        $path = './Public/Uploads/avatar/' . $this->memberInfo['id'] . '/';
        if (! is_dir($path)) {
            mkdir($path, 511, true);
        }
        $upload->savePath = $path;
        if (! $upload->upload()) { // 上传错误提示错误信息
            echo "<script>alert('" . $upload->getErrorMsg() . "');window.close();window.open('" . U('Member/upload') . "','_self'); </script>";
            // $this->ajaxReturn('', $upload->getErrorMsg(), 0, 'json');
        } else { // 上传成功 获取上传文件信息
            $info = $upload->getUploadFileInfo();
            $temp_size = getimagesize($path . $info['0']['savename']);
            if ($temp_size[0] < 100 || $temp_size[1] < 100) { // 判断宽和高是否符合头像要求
                                                              // $this->ajaxReturn(0, '图片宽或高不得小于100px！', 0, 'json');
                echo "<script>alert('图片宽或高不得小于100px！');window.close();window.open('" . U('Member/upload') . "','_self'); </script>";
            }
            $data['picName'] = $info['0']['savename'];
            $data['status'] = 1;
            $data['url'] = __ROOT__ . '/Public/Uploads/avatar/' . $this->memberInfo['id'] . '/' . $data['picName'];
            echo "<script>window.open('" . U('Member/upload') . "','_self');window.parent.uploaded('" . $data['status'] . "','" . $data['url'] . "');</script>";
        }
    }

    public function Dowtem()
    {
        $file = "./Public/template.xls";
        $this->Dow($file);
    }

    public function Dow($file)
    {
        if (file_exists($file)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename=' . basename($file));
            header('Content-Transfer-Encoding: binary');
            header('Expires: 0');
            header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));
            ob_clean();
            flush();
            readfile($file);
            exit();
        }
    }

    public function export()
    {
		//积分类
		$siteDB=D('Site');
		$inteClass=new Integral();
        $password = md5('123456');
        $xlsModel = M('Member');
        $xlsData = $xlsModel->where('site_id=' . __SITEID__)
            ->Field('id,name,username,tel,company_id')
            ->select();
        
        $groupData = M('member_group')->where('site_id=' . __SITEID__)
            ->Field('id,title,ismanager')
            ->select();
        
        $positionData = M('Member_position')->where('site_id=' . __SITEID__)
            ->Field('id,name')
            ->select();
        
        for ($i = 0; $i < 50; $i ++) {
                //当用户数量超过预定站点‘最大用户值’的时候报错
			if(!$siteDB->judgeMaxNum()){
				echo '<div style="color:#f71818">站点已达到最大人数</div>';
				exit();
			}
			
            if ($_POST['id'][$i] == '') {
                break;
            } else {
                
                $member[$i]['company_id'] = $_POST['id'][$i];
                
                foreach ($positionData as $pkey => $pval) {
                    
                    if (trim($_POST['member'][$i]) == trim($pval['id'])) {
					
					
                        $member[$i]['memberpositionid'] .=  $pval['id'] ;
                        $member[$i]['memberpositionname'] = $pval['name'];
						
                    }
                }
                
                $member[$i]['name'] = trim($_POST['name'][$i]);
                
                if ($_POST['sex'][$i] == 0) {
                    
                    $member[$i]['sex'] = 0;
                } elseif ($_POST['sex'][$i] == 1) {
                    $member[$i]['sex'] = 1;
                }
                
                foreach ($groupData as $gkey => $gval) {
                    
                    if (trim($_POST['role'][$i]) == $gval['id']) {
                          if($gval['ismanager']==1){
						$member[$i]['ismanager']=1;	
							}else{
						$member[$i]['ismanager']=0;			
							}
                        $member[$i]['group_id'] = $gval['id'];
                        $member[$i]['title'] = $gval['title'];
                    }
                }
                
                $member[$i]['password'] = $password;
                
                unset($is_ex);
                foreach($xlsData as $mmkey => $mmval){
					if($mmval['tel']==$_POST['phone'][$i]){
					$member[$i]['error']=1;
					$num=$i+1;
					$error_str.='第'.$num.'个用户电话已存在';
						}
					if($_POST['id'][$i]==$mval['company_id']){
					$num=$i+1;
					$member[$i]['error']=1;
					$num=$i+1;
					$error_str.='第'.$num.'个用户工号已存在';
						}	
					
					
					}
                
                $member[$i]['username'] = trim($_POST['phone'][$i]);
                
                $member[$i]['VerifyPhone'] = 0;
                $member[$i]['Verifycode'] = 0;
                
                $member[$i]['site_id'] = __SITEID__;
                $member[$i]['tel'] = $_POST['phone'][$i];
                $state = array(
                    '0' => '离职',
                    '1' => '正常',
                    '2' => '请假',
                    '3' => '旷工',
                    '4' => '出差',
                    '-1' => '禁用'
                );
                foreach ($state as $key => $st) {
                    if ($_POST['state'][$i] == $st) {
                        $member[$i]['state'] = $key;
                    }
                }
                
                $member[$i]['reg_time'] = strtotime($_POST['time'][$i]);
            }
        }
        
        $success = array();
        $error_data = array();
        $member_role = M('Member_role_user');
        
        $e_num = 0;
        $s_num = 0;
		
		
		
        foreach ($member as $mkey => $mval) {
			
            //当用户数量超过预定站点‘最大用户值’的时候报错
			if(!$siteDB->judgeMaxNum()){
				$mval['error']=1;
			}
			
			
			//如果有错误那么在这个if内会直接跳出这次循环
            if ($mval['error'] == 1) {
                foreach ($state as $key => $st) {
                    if ($mval['state'] == $key) {
                        $mval['state'] = $st;
                    }
			     }
				 
			    $edate=null;
				$esex=null;
                $edate = date('Y-m-d', $mval['reg_time']);
                $esex = $mval['sex'] == 0 ? '女' : '男';
                $error_str .= '<tr><td style="border-color:#f99494;">' . $mval['company_id'] . '</td>';
                $error_str .= '<td style="border-color:#f99494;">' . $mval['memberpositionname'] . '</td>';
                $error_str .= '<td style="border-color:#f99494;">' . $mval['name'] . '</td>';
                $error_str .= '<td style="border-color:#f99494;">' . $esex . '</td>';
                $error_str .= '<td style="border-color:#f99494;">' . $mval['title'] . '</td>';
                $error_str .= '<td style="border-color:#f99494;">' . $mval['tel'] . '</td>';
                $error_str .= '<td style="border-color:#f99494;">' . $mval['state'] . '</td>';
                $error_str .= '<td style="border-color:#f99494;">' . $edate . '</td></tr>';
                $e_num ++;
				continue;
            }
			
			
            
			//如果没有错误就会下来
            if ($mval['error'] == 0) {
                
				foreach ($state as $key => $st) {
                if ($mval['state'] == $key) {
                    $mval['state'] = $st;
                    }
				  }
				
				  
				$date=null;
                $sex=null;
                $date = date('Y-m-d', $mval['reg_time']);
                $sex = $mval['sex'] == 0 ? '女' : '男';
                $str .= '<tr><td style="border-color:#85d67a;">' . $mval['company_id'] . '</td>';
                $str .= '<td style="border-color:#85d67a;">' . $mval['memberpositionname'] . '</td>';
                $str .= '<td style="border-color:#85d67a;">' . $mval['name'] . '</td>';
                $str .= '<td style="border-color:#85d67a;">' . $sex . '</td>';
                $str .= '<td style="border-color:#85d67a;">' . $mval['title'] . '</td>';
                $str .= '<td style="border-color:#85d67a;">' . $mval['tel'] . '</td>';
                $str .= '<td style="border-color:#85d67a;">' . $mval['state'] . '</td>';
                $str .= '<td style="border-color:#85d67a;">' . $date . '</td></tr>';
                $s_num ++;
                $role_user = null;
				$pid=$mval['memberpositionid'];
				$mval['memberpositionid']=','.$mval['memberpositionid'].',';
				
                $role_id = $xlsModel->add($mval);
				
			
				 if($mval['ismanager']!=0){
				
				 $gd['member_id']=$role_id; 
				 $gd['member_name']=$mval['name']; 
				
				 M('member_position')->where('site_id = '.__SITEID__.' and id = '.$pid)->save($gd);	 
					 } 
				$inteClass->addIntegralNum($role_id);
                $role_user['role_id'] = $mval['group_id'];
                $role_user['user_id'] = $role_id;
                $role_user['site_id'] = __SITEID__;
                $member_role->add($role_user);
            }
        }
        
		
		if($s_num!=0||$e_num!=0){
		
        $res .= '<label>共导入' . $s_num . '条信息成功,有' . $e_num . '条信息失败</label>';
		
        $res .= '<table class="display table table-bordered table-hover table-striped">';
        $res .= $str;
        if ($error_str != '' && $str != '') {
            $res .= '<tr><td colspan="8" style=" border-color:#ffffff #ffffff #f99494 #ffffff; background-color:#ffffff;"> <hr></td></tr>';
        }
        $res .= $error_str;
        $res .= '</table>';
        
        echo $res;
		}
    }
}

